package com.dataease.indicatorqa.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataEaseApiClient {

    @Autowired
    private RestTemplate restTemplate;
    
    @Value("${dataease.url}")
    private String baseUrl;
    
    @Value("${dataease.token}")
    private String token;
    
    public List<Map<String, Object>> getTables() {
        String url = baseUrl + "/api/data/tables";
        HttpHeaders headers = createHeaders();
        
        ResponseEntity<List> response = restTemplate.exchange(
                url, HttpMethod.GET, new HttpEntity<>(headers), List.class);
        
        return response.getBody();
    }
    
    public List<Map<String, Object>> getIndicators(String tableCode) {
        String url = baseUrl + "/api/data/tables/" + tableCode + "/indicators";
        HttpHeaders headers = createHeaders();
        
        ResponseEntity<List> response = restTemplate.exchange(
                url, HttpMethod.GET, new HttpEntity<>(headers), List.class);
        
        return response.getBody();
    }
    
    public Map<String, Object> queryIndicatorData(String indicatorId, String filters) {
        String url = baseUrl + "/api/visualization/query";
        HttpHeaders headers = createHeaders();
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("indicatorId", indicatorId);
        requestBody.put("filters", filters);
        
        ResponseEntity<Map> response = restTemplate.exchange(
                url, HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
        
        return response.getBody();
    }
    
    public Map<String, Object> executeQuery(String sql) {
        String url = baseUrl + "/api/query/execute";
        HttpHeaders headers = createHeaders();
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sql", sql);
        
        ResponseEntity<Map> response = restTemplate.exchange(
                url, HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
        
        return response.getBody();
    }
    
    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);
        headers.set("Content-Type", "application/json");
        return headers;
    }
}